package com.wac.data.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wac.data.service.UserService;
import com.wac.data.utils.UpLoad;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 集成腾讯云存储的文件上传
 */

@RestController
@RequestMapping("/upload")
public class UploadFileController {

	private static ObjectMapper objectMapper = new ObjectMapper();

	//文件夹路径
	private static String BASE_URL = "D:/webAssets/image";

	//服务器域名
	private static String DOMAIN = "192.168.31.118:8080";

	@Resource
	private UserService userService;

	//需要带token确认用户 1代表传头像 2代表传个人背景封面 3代表文章配图 4动态配图
	@RequestMapping("/img")
	public String upLoadImg(HttpServletRequest request, @RequestParam("file") List<MultipartFile> file, String id, int where) {
		// if (null == file) {
		// 	return "文件为空";
		// }
		// if (userService.upLoadFile(id, file, where)) {
		// 	return "1";
		// }
		return "0";
	}

	//文件上传本地版 -- 测试接口 非正式
	@RequestMapping("/test")
	public String upLoadtest(@RequestParam("file") List<MultipartFile> file) throws JsonProcessingException {
		Map<String, Object> result = new HashMap<>();
		MultipartFile theFile = file.get(0);
		String fileNmae = "我重置了名称";
		String suffixName = theFile.getOriginalFilename().substring(theFile.getOriginalFilename().indexOf("."));
		String filePath = BASE_URL + "/user_head/" + fileNmae + suffixName;
		File fileTempObj = new File(filePath);
		try {
			theFile.transferTo(fileTempObj);
		} catch (Exception e) {
			result.put("error", e.getMessage());
			return objectMapper.writeValueAsString(result);
		}
		result.put("success", "文件上传成功!");
		result.put("url", DOMAIN + "/image/user_head/" + fileNmae + suffixName);
		return objectMapper.writeValueAsString(result);
	}

	@RequestMapping("/local/img")
	public String upLoadimages(@RequestParam("file") List<MultipartFile> file, int where) throws JsonProcessingException {
		return objectMapper.writeValueAsString(new UpLoad().upLoadFiles(file, where));
	}
}
